package com.eshop.logging.tools.controller;

import com.zhonghui.license.AbstractServerInfos;
import com.zhonghui.license.LinuxServerInfos;
import com.zhonghui.license.WindowsServerInfos;
import com.zhonghui.license.LicenseCheckModel;
import java.io.IOException;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Base64;
import java.io.File;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
import com.zhonghui.license.LicenseVerify;
import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.annotation.AnonymousAccess;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.eshop.config.RestConfig;
import com.eshop.exception.BadRequestException;
import com.eshop.utils.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import com.eshop.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({ "/api/license" })
public class LicenseController
{
    private String productId;
    @Value("${product.company}")
    private String company;
    @Value("${product.url}")
    private String url;
    @Autowired
    private RedisUtils redisUtils;
    
    public LicenseController() {
        this.productId = "zhonghui";
    }
    
    @AnonymousAccess
    @PostMapping({ "/apply" })
    public ResponseEntity<Object> applyBySMS(@RequestBody final ApplyParam applyParam) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        final String code = (String)this.redisUtils.get(applyParam.getMobilePhone());
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("短信验证码不存在或已过期");
        }
        if (StringUtils.isBlank(applyParam.getCode()) || !applyParam.getSmsCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("短信验证码错误");
        }
        applyParam.setLicenseId(applyParam.getLicenseId());
        applyParam.setCompanyName(this.company);
        applyParam.setLicenseCheckModel(this.getServerInfos());
        final RestTemplate restTemplateHttps = new RestTemplate(RestConfig.generateHttpRequestFactory());
        final ResponseEntity<String> result = (ResponseEntity<String>)restTemplateHttps.postForEntity(this.url + "/license/generateLicense", (Object)applyParam, (Class)String.class, new Object[0]);
        final HashMap map = JsonUtil.fromJson(result.getBody(), HashMap.class);
        if ("ok".equals(map.get("result"))) {
            final String saveDir = System.getProperty("user.dir");
            this.base64ToFile((String) map.get("msg"), this.productId + ".lic", saveDir);
            return ResponseEntity.ok(map.get("result"));
        }
        throw new BadRequestException((String)map.get("msg"));
    }
    
    @AnonymousAccess
    @GetMapping({ "/getLicense" })
    public ResponseEntity<Object> getLicense() {
        final LicenseVerify licenseVerify = new LicenseVerify();
        final boolean verifyResult = licenseVerify.verify();
        if (verifyResult) {
            return (ResponseEntity<Object>)ResponseEntity.ok((Object)"证书校验成功");
        }
        final Map result = new HashMap();
        result.put("message", "您的证书无效，请核查服务器是否取得授权或重新申请证书！");
        result.put("status", 1000);
        throw new BadRequestException("证书校验失败");
    }
    
    public void base64ToFile(final String base64, final String fileName, final String savePath) {
        File file = null;
        final String filePath = savePath;
        final File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            final byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        }
        catch (Exception e) {
            e.printStackTrace();
            if (bos != null) {
                try {
                    bos.close();
                }
                catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                }
                catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        finally {
            if (bos != null) {
                try {
                    bos.close();
                }
                catch (IOException e3) {
                    e3.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                }
                catch (IOException e3) {
                    e3.printStackTrace();
                }
            }
        }
    }
    
    private LicenseCheckModel getServerInfos() {
        final String osName = System.getProperty("os.name").toLowerCase();
        AbstractServerInfos abstractServerInfos = null;
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        }
        else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }
        else {
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }
}
